using StudyCompanion.Commons.Encrypt;
using StudyCompanion.Core.Repository;
using StudyCompanion.Core.Services;
using StudyCompanion.Dto.Web;
using StudyCompanion.Entity.User;
using StudyCompanion.IServices;

namespace StudyCompanion.Services;

public class WebRegisService : BaseService, IWebRegisService
{
    private readonly IUserService _useRepository;
    private readonly BaseRepository<Users> _userRepository;

    public WebRegisService(IUserService useRepository, BaseRepository<Users> userRepository)
    {
        _useRepository = useRepository;
        _userRepository = userRepository;
    }

    /// <summary>
    ///     H5注册
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<Tuple<bool, string>> AddUser(AddUserDto dto)
    {
        var isSuperUser = await _useRepository.GetUserbyId(dto.SuperiorUser);
        if (!isSuperUser.Item1) return new Tuple<bool, string>(false, "分享人信息有误");
        var code = RedisHelper.Get($"telSMS:{dto.Phone}");
        if (code != dto.Code) return new Tuple<bool, string>(false, "校验码错误");
        RedisHelper.Del($"telSMS:{dto.Phone}");
        var isUser = await _useRepository.GetUserbyPhone(dto.Phone);
        if (isUser.Item1) return new Tuple<bool, string>(false, "手机号已注册");
        var userInfo = new Users
        {
            Phone = dto.Phone,
            Password =  BCrypt.Net.BCrypt.HashPassword(dto.Password),
            SuperiorUser = dto.SuperiorUser,
            NickName = dto.NickName
        };

        await _userRepository.InsertAsync(userInfo);
        return new Tuple<bool, string>(true, "注册成功");
    }
}